package pheromoneMap;

import java.awt.*;
import javax.swing.*;

public class PheromoneCanvas extends JPanel {
	static final long serialVersionUID = 1;
	static final boolean PRINT_DEBUG = false;
	public static final double MAX_MAGNITUDE_DRAWN = 10.0;

	PheromoneMap m_parent;
	static final int blockSize = 20;
	private static PheromoneType type = PheromoneType.TO_HOME;

	public PheromoneCanvas( PheromoneMap parent ) {
		m_parent = parent;
		this.setBackground( Color.white );
	}

	public void paintComponent( Graphics g ) {
		super.paintComponent( g );
		Graphics2D g2d = (Graphics2D) g;

		// Construct a polygon arrow
		int xPoints[] = new int[3];
		int yPoints[] = new int[3];

		double offset = 3 * Math.PI / 4;

		// Point 1 -- arrow tip
		xPoints[0] = (blockSize / 2);
		yPoints[0] = 0;

		// Point 2 -- bottom left (tip - 3/4 PI)
		xPoints[1] = (int) ((blockSize / 2) * Math.cos( offset ));
		yPoints[1] = (int) ((blockSize / 2) * Math.sin( offset ));

		// Point 3 -- bottom right (tip + 3/4 PI)
		xPoints[2] = (int) ((blockSize / 2) * Math.cos( - offset ));
		yPoints[2] = (int) ((blockSize / 2) * Math.sin( - offset ));

		
		Polygon arrow = new Polygon( xPoints, yPoints, 3 );

		// Draw the full canvas
		double magnitude, direction;

		java.text.DecimalFormat df = new java.text.DecimalFormat( "#.#" );
		g2d.translate( blockSize / 2, - blockSize / 2 );
		for( int i = 0; i < m_parent.m_mapWidth; i++ ) {
			for( int j = 0; j < m_parent.m_mapHeight; j++ ) {
				
				magnitude = m_parent.getMagnitude( i, j, type );
				direction = m_parent.getDirection( i, j, type);

				int alpha = Math.min( 255, (int) (255 * magnitude / MAX_MAGNITUDE_DRAWN) );
				g2d.setColor( new Color( 128, 128, 255, alpha ) );
				
				g2d.translate( 0, blockSize );
				g2d.rotate( direction );

				g2d.fillPolygon( arrow );
				g2d.drawPolygon( arrow );				
				
				g2d.rotate( - direction );
				
				if( PRINT_DEBUG && magnitude >= 0.1 ) {
					g2d.setColor( new Color( 0, 0, 0, 255));
					g2d.drawString( df.format(magnitude), -blockSize/2, blockSize/2);
				}
			}
			g2d.translate( blockSize, - m_parent.m_mapHeight * blockSize );
		}
	}

	public void update( Graphics g ) {
		super.update( g );
	}
	
	public static void pheromoneTypeToVisualize(PheromoneType type) {
		PheromoneCanvas.type = type;
	}
}
